# -*- coding: utf-8 -*-
import os
import sqlite3

class DatasetDB(object):

	def __init__(self,workspace,categories):
		self.workspace = workspace
		self.categories = categories

		if not os.path.exists(self.workspace + os.sep + "dataset.db"):
			file = open(workspace + os.sep + "dataset.db","w")
			self.conn = sqlite3.connect(self.workspace + os.sep + "dataset.db")
			self.cursor = self.conn.cursor()
			self.cursor.execute("CREATE TABLE dataset(word TEXT, category TEXT, value REAL)")				
			self.conn.commit()
		else:
			self.conn = None
			self.conn = sqlite3.connect(self.workspace + os.sep + "dataset.db")
			self.cursor = self.conn.cursor()

	def categoryMap(self):
		current = {}
		for c in self.categories:
			current[c] = 0

		return current

	def loadStructure(self):
		self.cursor.execute("SELECT word,category,value FROM dataset")
		structure = self.cursor.fetchall()

		wordset = {}
		for s in structure:
			if not (s[0] in wordset):					
				wordset[unicode(s[0])] = self.categoryMap()
			wordset[unicode(s[0])][s[1]] = s[2]

		return wordset

	def addWord(self,word,category,value):
		word = unicode(word)
		category = unicode(category)		
		params = (word, category, value,)
		self.cursor.execute("INSERT INTO dataset VALUES(?,?,?)", params)
		self.conn.commit()

	def isEmpty(self):
		return ((self.cursor.execute("SELECT count(*) FROM dataset")).fetchall()[0][0] == 0)